package com.zwcl.glass.tools.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zwcl.glass.tools.entity.ArticleComment;
import com.zwcl.glass.tools.mapper.ArticleCommentMapper;
import com.zwcl.glass.tools.service.ArticleCommentService;
import com.zwcl.common.mybatis.service.impl.BaseServiceImpl;
import com.zwcl.glass.tools.vo.ArticleCommentVo;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xieyongping
 * @since 2021-01-11
 */
@Service
public class ArticleCommentServiceImpl extends BaseServiceImpl<ArticleCommentMapper, ArticleComment> implements ArticleCommentService {

    @Override
    public List<ArticleCommentVo> getArticleComments(Long articleId) {
        //查询数据
        List<ArticleComment> commentList=this.list(new LambdaQueryWrapper<ArticleComment>().eq(ArticleComment::getDelFlag,false).orderByAsc(ArticleComment::getCreateTime));
        Map<Integer,List<ArticleComment>> commentMap = commentList.stream().collect(Collectors.groupingBy(ArticleComment::getParentId));
        List<ArticleComment> parentList = commentMap.get(0);
        List<ArticleCommentVo> articleCommentVos=new ArrayList<>();
        for(ArticleComment articleComment : parentList){
            ArticleCommentVo articleCommentVo =new ArticleCommentVo();
            List<ArticleComment> childsList = recursionFindChilds(articleComment.getId(),commentMap);
            Collections.sort(childsList, new Comparator<ArticleComment>() {
                @Override
                public int compare(ArticleComment A1, ArticleComment A2) {
                    return A1.getCreateTime().compareTo(A2.getCreateTime());
                }
            });
            articleCommentVo.setParent(articleComment);
            articleCommentVo.setChilds(childsList);
            articleCommentVos.add(articleCommentVo);
        }
        return articleCommentVos;
    }

    private List<ArticleComment> recursionFindChilds(Integer parentId, Map<Integer,List<ArticleComment>> commentMap ){
        List<ArticleComment> articleComments=new ArrayList<>();
        if(commentMap.containsKey(parentId)){
            //子评论
            List<ArticleComment> childs=commentMap.get(parentId);
            if(childs!=null && childs.size()>0) {
                articleComments.addAll(childs);
                for (ArticleComment articleComment : childs) {
                    articleComments.addAll(recursionFindChilds(articleComment.getId(), commentMap));
                }
            }
        }
        return articleComments;
    }
}
